﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace VSM
{
    public partial class PackageSetup : System.Web.UI.Page
    {
        private static GeneralFunctions GF = null;
        private static string dbType;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            
            if (!IsPostBack)
            {
                Services sv = new Services();
                dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet dsModel = sv.ExecuteQuery("VSM", "Select -1 as ModelCode, 'Choose Model' as ModelName  UNION ALL select ModelCode, ModelName from U_Model");
                ddl_Model.DataSource = dsModel.Tables[0];
                ddl_Model.DataTextField = "ModelName";
                ddl_Model.DataValueField = "ModelCode";
                ddl_Model.DataBind();

                DataSet dsPackage = sv.ExecuteQuery("VSM", "select -1 as PackageID, 'Choose Package' as PackageName Union All select PackageID, PackageName from U_Package");
                ddl_Package.DataSource = dsPackage.Tables[0];
                ddl_Package.DataTextField = "PackageName";
                ddl_Package.DataValueField = "PackageID";
                ddl_Package.DataBind();
            }
        }

        private string FormatDate(string dateIn) {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");
            
        }
        

        private void loadDetail() {
            string ModelCode = ddl_Model.SelectedValue.ToString();
            string PackageID = ddl_Package.SelectedValue.ToString();
            if (ModelCode != "-1")
            {
                if (PackageID != "-1")
                {
                    string sql = "select ROW_NUMBER() OVER (ORDER BY PacDetID) AS No, PacDetID, ModelCode, PackageID, ItemCode, ItemName, FrgnName, Quantity, Remarks from U_PackageDetail ";
                    sql += " where  ModelCode = " + ModelCode + " and PackageID = " + PackageID;

                    Services sv = new Services();
                    Session["PackageDetail"] = sv.ExecuteQuery("VSM", sql).Tables[0];
                    grvPO.DataSource = (DataTable)Session["PackageDetail"];
                    grvPO.DataBind();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Please choose a package.');", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Please choose a model.');", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
           
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
          
            //txtPONo.Text = "PO-" + "003/0414";
            //txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
      
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //if (txtDealerCode.Text == "")
            //{
            //    Session["errorMessage"] = "Missing Dealer Code";
            //    Session["requestXML"] = "";
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Dealer Code','');", true);
            //}
            /*
            String requestXML = _collectData();
            Transaction ts = new Transaction();

            DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.BUSINESS_PARTNER).ToString(), txtDealerCode.Text, !string.IsNullOrEmpty(DealerCode.Value), Utils.AppConstants.VSM
            );

            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
       
             */
        }
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               // Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
               // this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
            //UpdatePrice();
        }

        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {

            /*this.txtVendorCode.Text = "";
            this.txtVendorName.Text = "";
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnUpdate.Enabled = false;*/
        }

       
      
        protected void TextBox_Change(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            string ItemCode = tb.Text;
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lbl_No");
            int rowNo = Int32.Parse(lblNo.Text) - 1;
            int index = 0;
            DataTable dtTmp = (DataTable)Session["PackageDetail"];
            foreach (DataRow dr in dtTmp.Rows)
            {
                if (rowNo == index)
                {
                    MasterData mt = new MasterData();
                    DataRow drNew = GetLineInfo(ItemCode, 1);
                   
                    if (drNew != null)
                    {

                        dr["ItemCode"] = ItemCode;
                        dr["ItemName"] = drNew["ItemName"];
                        dr["FrgnName"] = drNew["FrgnName"];
                        dr["Quantity"] = 1;
                        Session["PackageDetail"] = dtTmp;
                        grvPO.DataSource = dtTmp;
                        grvPO.DataBind();
                       
                        this.lblError.Visible = false;
                        break;
                    }
                   
                    else
                    { //=0
                        this.lblError.Text = "There is no part with code [" + tb.Text + "] available ";
                        this.lblError.Visible = true;
                    }
                }
                index++;
            }
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            DataTable dtTmp = (DataTable)Session["PackageDetail"];
            DataRow dr = dtTmp.NewRow();
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["PacDetID"] = -1;
            dr["ModelCode"] = ddl_Model.SelectedValue.ToString();
            dr["PackageID"] = ddl_Package.SelectedValue.ToString();
            dr["ItemCode"] = "";
            dr["ItemName"] = "";
            dr["FrgnName"] = "";
            dr["Quantity"] = 1;
            dtTmp.Rows.Add(dr);
            this.grvPO.DataSource = dtTmp;
            this.grvPO.DataBind();
            Session["PackageDetail"] = dtTmp;
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    Label lblNo = myRow.FindControl("lblNo") as Label;
            //    lblNo.Text = (myRow.RowIndex + 1).ToString();
            //    //if (this.hdnStatus.Value == "C")
            //    //{
            //    //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
            //    //    txtQuantity.Enabled = false;
            //    //}
            //}
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        private void saveGrid()
        {
            DataTable dtTmp = (DataTable)Session["PackageDetail"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in grvPO.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["No"] = ((Label)row.FindControl("lbl_No")).Text;
                newRow["PacDetID"] = ((Label)row.FindControl("lbl_PacDetID")).Text;
                newRow["ModelCode"] = ((Label)row.FindControl("lbl_ModelCode")).Text;
                newRow["PackageID"] = ((Label)row.FindControl("lbl_PackageID")).Text;
                newRow["ItemCode"] = ((TextBox)row.FindControl("txt_ItemCode")).Text;
                newRow["ItemName"] = ((Label)row.FindControl("lbl_ItemName")).Text;
                newRow["FrgnName"] = ((Label)row.FindControl("lbl_FrgnName")).Text;
                newRow["Quantity"] = ((TextBox)row.FindControl("txt_Qty")).Text;
              
                dtTmp.Rows.Add(newRow);
            }
            Session["PackageDetail"] = dtTmp;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                saveGrid();
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lbl_No");
                int rowNo = Int32.Parse(lblNo.Text);
                DataTable dtTmp = (DataTable)Session["PackageDetail"];
                Services sv = new Services();
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString()))
                    {
                        string DetID = dr["PacDetID"].ToString();
                        if (DetID != "-1")
                        {
                            DataSet dsDel = new DataSet();
                            DataTable dtDel = new DataTable();
                            dtDel.Columns.Add("PacDetID");
                            DataRow drDel = dtDel.NewRow();
                            drDel["PacDetID"] = DetID;

                            dtDel.Rows.Add(drDel);
                            dsDel.Tables.Add(dtDel);
                            sv.DeletePackageDetail("VSM", dsDel);
                        }
                        dr.Delete();
                        break;
                    }
                }
                //reset number
                dtTmp.AcceptChanges();
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["No"] = ++index;

                Session["PackageDetail"] = dtTmp;
                grvPO.DataSource = dtTmp;
                grvPO.DataBind();
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Delete] Action complete.');", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Delete] Action incomplete.');", true);
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }
              
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
               
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }


        private DataRow GetLineInfo(string ItemCode, double qty)
        {
            try
            {
                DataTable dtTmp = (DataTable)Session["PackageDetail"];
                DataRow dr = dtTmp.NewRow();
                GetDefault defaultWS = new GetDefault();
                MasterData mt = new MasterData();
                DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(), "'" + ItemCode + "'");

                DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(),
                    Session[Utils.AppConstants.ID_Dealer].ToString(), ItemCode, qty, DateTime.Now, Session[Utils.AppConstants.U_Department].ToString(), "4");

                dr["PacDetID"] = -1;
                dr["No"] = dtTmp.Rows.Count + 1;
                dr["ItemCode"] = ItemCode;
                dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
                dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
                dr["Quantity"] = qty;
                return dr;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            saveGrid();
            DataSet dsDetail = new DataSet();
            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("PacDetID");
            dtDetail.Columns.Add("ModelCode");
            dtDetail.Columns.Add("PackageID");
            dtDetail.Columns.Add("ItemCode");
            dtDetail.Columns.Add("ItemName");
            dtDetail.Columns.Add("FrgnName");
            dtDetail.Columns.Add("Quantity");

            Services svc = new Services();
            DataTable dtTmp = (DataTable)Session["PackageDetail"];
            foreach (DataRow drDetail in dtTmp.Rows)
            {
                dsDetail.Tables.Clear();
                DataRow toAdd = dtDetail.NewRow();

                toAdd["PacDetID"] = drDetail["PacDetID"];
                toAdd["ModelCode"] = drDetail["ModelCode"];
                toAdd["PackageID"] = drDetail["PackageID"];

                toAdd["ItemCode"] = drDetail["ItemCode"];
                toAdd["ItemName"] = drDetail["ItemName"];
                toAdd["FrgnName"] = drDetail["FrgnName"];
                toAdd["Quantity"] = drDetail["Quantity"];
               
                dtDetail.Rows.Clear();
                dtDetail.Rows.Add(toAdd);
                dsDetail.Tables.Add(dtDetail);


                if (drDetail["PacDetID"].ToString() == "-1")
                    svc.InsertPackageDetail("VSM", dsDetail);
                else
                    svc.UpdatePackageDetail("VSM", dsDetail);

            }
            loadDetail();
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Update] Operation complete.');", true);
        }

        protected void btn_Load_Click(object sender, EventArgs e)
        {
            loadDetail();
        }

        
    }

}